import { getDateFormat } from '@renderer/utils/myDate'
// import { dayjs } from 'element-plus'
import { ref } from 'vue'

export default () => {
  const logs = ref<LogModel[]>([])
  const log = ref<LogModel>()

  const all = async (args?: Record<string, any>) => {
    let sql = `select * from logs order by date desc`
    if (args?.date) sql = `select * from logs where date like @date order by date desc`
    logs.value = await window.api.sql(sql, 'findAll', { date: `%${args?.date}%` })
  }

  const find = async (id: number) => {
    log.value = await window.api.sql(`select * from logs where id=@id`, 'findOne', { id })
  }

  const add = async (data: LogModel) => {
    // const date = dayjs(new Date().getDate() + 1).format('YYYY-MM-DD')
    // console.log(new Date().getDate())
    // const today = dayjs()
    // const tomorrow = today.add(1, 'day')
    // console.log(tomorrow)
    // const date = tomorrow.format('YYYY-M-DD')
    // console.log(today)
    const { date, content } = data
    return await window.api.sql(
      `insert into logs (date,content,created_at) values(@date,@content,datetime())`,
      'insert',
      {
        date,
        content
      }
    )
  }

  const update = async (data: LogModel) => {
    const { content, id } = data
    const date = getDateFormat(content)
    await window.api.sql(`update logs set date=@date,content=@content where id=@id`, 'update', {
      date,
      content,
      id
    })
  }

  const del = async (id: number) => {
    await window.api.sql(`delete from logs where id=@id`, 'del', { id })
  }

  return { all, find, add, del, update, log, logs }
}
